<?php
/**
 * 同城微聚汇
 * ============================================================================
 * * 版权所有 2015-2027 武汉鼎联信息技术有限公司，并保留所有权利。
 * 网站地址: http://dlshop.dliansoft.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 2015-11-21
 */
namespace app\mobile\controller;

use app\home\logic\UsersLogic;
use app\home\model\Message;
use think\Page;
use think\Request;
use think\Verify;
use think\db;
use PDO;
class User extends MobileBase
{

    public $user_id = 0;
    public $user = array();

    /*
    * 初始化操作
    */
    public function _initialize()
    {
        parent::_initialize();

        $nologin = array(
            'login', 'pop_login', 'do_login', 'logout', 'verify', 'set_pwd', 'finished',
            'verifyHandle', 'reg', 'send_sms_reg_code', 'find_pwd', 'check_validate_code',
            'forget_pwd', 'check_captcha', 'check_username', 'send_validate_code', 'express',
        );
        if (!$this->user_id && !in_array(ACTION_NAME, $nologin)) {
            header("location:" . U('Mobile/Index/error_msg'));
            exit;
        }
        //道讯销售记录查询
        parent::sync_sell_list();
        $order_status_coment = array(
            'WAITPAY' => '待付款 ', //订单查询状态 待支付
            'WAITSEND' => '待发货', //订单查询状态 待发货
            'WAITRECEIVE' => '待收货', //订单查询状态 待收货
            'WAITCCOMMENT' => '待评价', //订单查询状态 待评价
        );
        $this->assign('order_status_coment', $order_status_coment);


    }

    /*
     * 用户中心首页
     */
    public function index()
    {
        //push_wxmessage($this->user_id,$tplarr,'news');
        $goods_collect_count = M('goods_collect')->where("user_id", $this->user_id)->count(); // 我的商品收藏
        $comment_count = M('comment')->where("user_id", $this->user_id)->count();   // 我的评论数
        //$coupon_count = M('coupon_list')->where("uid", $this->user_id)->count(); // 我的优惠券数量
        $coupon_count = M('coupon_list')->where(array('uid'=>$this->user_id,'use_time'=>'0'))->count(); // 我的优惠券数量
        $level_name = M('user_level')->where("level_id", $this->user['level'])->getField('level_name'); // 等级名称
        $profit_name = M('user_level_distribution')->where("level_id", $this->user['profit_level'])->getField('level_name'); // 收益等级名称
        $order_count = M('order')->where("user_id", $this->user_id)->count(); //我的全部订单 (改)
        $count_return = M('return_goods')->where("user_id=$this->user_id and status<2")->count();   //退换货数量
        $wait_pay = M('order')->where("user_id=$this->user_id and pay_status =0 and order_status = 0  and pay_code != 'cod'")->count(); //我的待付款 (改)
        $wait_receive = M('order')->where("user_id=$this->user_id and order_status= 1 and shipping_status= 1")->count(); //我的待收货 (改)
        $comment = DB::query("select COUNT(1) as comment from __PREFIX__order_goods as og left join __PREFIX__order as o on o.order_id = og.order_id where o.user_id = $this->user_id and og.is_send = 1 and og.is_comment = 0 ");  //我的待评论订单
        
       // $district_count = DB::query("select count(*) from v_share_record_count where user_id = $this->user_id and on_time <=".time()." and off_time >= ".time());  //我的分销
        $district_count =M('share_record t1')->join('tp_goods t2','t1.goods_id=t2.goods_id and t2.is_on_sale=1','left')->join('tp_users t3','t1.s_user_id=t3.user_id','left')->where('t1.user_id = '.$this->user_id.'  or t1.first_user_id = '.$this->user_id)->where('t2.on_time <= '.time().' and t2.off_time >='.time())->count();

        
        $wait_comment = $comment[0][comment];
        $count_sundry_status = array($wait_pay, $wait_receive, $wait_comment, $count_return);
        $userinfo = M('users')->field('user_money,pay_points,mobile,distribut_money,birthday,level')->where('user_id',$this->user_id)->find();


        //将会员信息更新到道讯数据库
        $UsersLogic=new UsersLogic();
        $UsersLogic->run_storedprocedure($userinfo['mobile'],$userinfo['birthday'],$userinfo['level']);

        $this->assign('mobile',$userinfo['mobile']);
        $this->assign('userinfo',$userinfo);
        $this->assign('level_name', $level_name);
        $this->assign('profit_name', $profit_name);
        $this->assign('order_count', $order_count); // 我的订单数 （改）
        $this->assign('goods_collect_count', $goods_collect_count);
        $this->assign('comment_count', $comment_count);
        $this->assign('coupon_count', $coupon_count);
        $this->assign('count_sundry_status', $count_sundry_status);  //各种数量
         $this->assign('wait_pay', $wait_pay);
         $this->assign('wait_receive', $wait_receive);
         $this->assign('wait_comment', $wait_comment);
         $this->assign('count_return', $count_return);
         $this->assign('district_count', $district_count);
        return $this->fetch('index2');
    }
     /*
     * 我的分销商
     */
    public function mydistribut()
    {


        $district_one_count =M('share_record t1')->join('tp_goods t2','t1.goods_id=t2.goods_id and t2.is_on_sale=1','left')->join('tp_users t3','t1.s_user_id=t3.user_id','left')->where('t1.user_id = '.$this->user_id)->where('t2.on_time <= '.time().' and t2.off_time >='.time())->count();//一级分销统计
        $district_two_count =M('share_record t1')->join('tp_goods t2','t1.goods_id=t2.goods_id and t2.is_on_sale=1','left')->join('tp_users t3','t1.s_user_id=t3.user_id','left')->where('t1.first_user_id = '.$this->user_id)->where('t2.on_time <= '.time().' and t2.off_time >='.time())->count();//二级级分销统计
        $waitpay_order_count=M('order_goods t0')->field('t3.head_pic,t3.nickname,t0.goods_name, t0.goods_num,t0.member_goods_price ,t1.order_status,t1.pay_status')->join('tp_order t1','t0.order_id=t1.order_id','left')->join('tp_share_record t2','(t1.user_id = t2.s_user_id or t1.user_id = t2.first_user_id) and t0.goods_id = t2.goods_id','left')->join('tp_users t3','t1.user_id = t3.user_id','left')->where('t1.pay_status',0)->where('t2.user_id',$this->user_id)->count();
        $waitreciv_order_count=M('order_goods t0')->field('t3.head_pic,t3.nickname,t0.goods_name, t0.goods_num,t0.member_goods_price ,t1.order_status,t1.pay_status')->join('tp_order t1','t0.order_id=t1.order_id','left')->join('tp_share_record t2','(t1.user_id = t2.s_user_id or t1.user_id = t2.first_user_id) and t0.goods_id = t2.goods_id','left')->join('tp_users t3','t1.user_id = t3.user_id','left')->where('t1.order_status=1 or (t1.pay_status=1 and t1.order_status=0)')->where('t2.user_id',$this->user_id)->count();
        
        $over_order_count=M('order_goods t0')->field('t3.head_pic,t3.nickname,t0.goods_name, t0.goods_num,t0.member_goods_price ,t1.order_status')->join('tp_order t1','t0.order_id=t1.order_id','left')->join('tp_share_record t2','(t1.user_id = t2.s_user_id or t1.user_id = t2.first_user_id) and t0.goods_id = t2.goods_id','left')->join('tp_users t3','t1.user_id = t3.user_id','left')->where('t1.order_status',4)->where('t2.user_id',$this->user_id)->count();

        $this->assign('district_one_count', $district_one_count);
        $this->assign('district_two_count', $district_two_count);
        $this->assign('waitpay_order_count', $waitpay_order_count);
        $this->assign('waitreciv_order_count', $waitreciv_order_count);
        $this->assign('over_order_count', $over_order_count);
        return $this->fetch();
    }
    /*
     * 我的分销商
     */
    public function mydistribut_list()
    {
        $level = I('get.level');
        if($level==1){
             $where='t1.user_id = '.$this->user_id;
           
        }elseif($level==2){
            $where='t1.first_user_id = '.$this->user_id;
         
        }
         $district=M('share_record t1')->join('tp_goods t2','t1.goods_id=t2.goods_id and t2.is_on_sale=1','left')->join('tp_users t3','t1.s_user_id=t3.user_id','left')->field('t1.id,t1.user_id,t1.s_user_id,t3.head_pic,t3.nickname,t2.goods_id,t2.goods_name,t2.original_img,t1.goods_id,t1.s_id ,t1.first_user_id')->where($where)->where('t2.on_time <= '.time().' and t2.off_time >='.time())->select();
        /*$disarr=array();
        $arrstr=array();
        foreach ($district as $key => $value) {
            $key=array_search($value['goods_id'],$arrstr);
            if(!$key){
                $disarr['goods_id']=$value['goods_id'];
                $disarr['goods_name']=$value['goods_name'];
                $disarr['original_img']=$value['original_img'];
                $disarr['districts'][]=array('head_pic'=>$value['head_pic'],'nickname'=>$value['nickname']);
                $disgoods[]=$disarr;
                $arrstr[]=$value['goods_id'];
            }else{
                $disgoods[$key]['districts'][]=array('head_pic'=>$value['head_pic'],'nickname'=>$value['nickname']);
            }
        }*/
  
        $this->assign('district', $district);

        return $this->fetch();
    }
    /*
     * 我的分销订单列表
     */
    public function mydistribut_orderlist()
    {
         $statu = I('get.statu');
         if($statu==1){
            $condit=array('t1.pay_status'=>0);
         }
         if($statu==2){
            $condit='t1.order_status=1 or (t1.order_status=0 and pay_status=1)';
         }
           if($statu==3){
            $condit=array('t1.order_status'=>4);
         }


         $distr_orders=M('order_goods t0')->field('t3.head_pic,t3.nickname,t0.goods_name, t0.goods_num,t0.member_goods_price ,t1.order_status,t1.pay_status')->join('tp_order t1','t0.order_id=t1.order_id','left')->join('tp_share_record t2','(t1.user_id = t2.s_user_id or t1.user_id = t2.first_user_id) and t0.goods_id = t2.goods_id','left')->join('tp_users t3','t1.user_id = t3.user_id','left')->where($condit)->where('t2.user_id',$this->user_id)->select();

        $this->assign('distr_orders', $distr_orders);
        return $this->fetch();
    }

     public function unfreeze()
    {
        $profit_name = M('user_level_distribution')->where("level_id", $this->user['profit_level'])->getField('level_name'); // 收益等级名称
         $this->assign('profit_name', $profit_name);
        return $this->fetch();
    }
  
    /*查询用户*/
     public function search_user(){
        if(IS_AJAX){
            $kw=I('get.kw');
            $p=(int)I('get.p');
            $size=(int)I('get.size');
            if(preg_match("/^1[34578]{1}\d{9}$/",$kw)){  
                $field='head_pic,nickname,mobile,user_id';
                $where['mobile']=$kw;
            }else{  
                $field='head_pic,nickname,user_id';
                $where['nickname']=array('like','%'.base64_encode($kw).'%');
            }
            $count=M('users')->field($field)->where($where)->count();
            $Page = new Page($count, $size);
            $showpage = $Page->show();
            $res=M('users')->field($field)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order('user_id')->select();
            if($p*$size<$count){
                $list['isnext']=1;
            }else{
                $list['isnext']=0;
            }

            foreach ($res as $key => $va) {
                $mobile=hidtel($va['mobile']);
               $nickname=hidtel(shownickname($va['nickname'])) ;
                $htmlstr.='<li class="list_add J_add" data="'.$va['user_id'].'"><div class="td_l"><p><img src="'.$va['head_pic'].'" width="40" class="headpic"></p><p class="nickname">'.$nickname.'</p></div><div class="td_r"><p class="time">'.$mobile.'</p></div></li>';
            }
            $list['data']=$htmlstr;
            $this->ajaxReturn($list,'json');
            exit;
            
        }

        $type=I('get.type');
        /*如果是赠送优惠券就查询出优惠券列表*/
        if($type=="give_coupon"){
            $coupon=M("coupon_list t0")->field('t1.name,t0.id,t0.cid,t1.use_start_time,t1.use_end_time')->join('tp_coupon t1','t0.cid=t1.id','left')->where('t1.use_start_time<='.time().' and t1.use_end_time>='.time().' and t0.uid='.$this->user_id)->select();

            foreach ($coupon as $key => $value) {
                $coup_str.='<option value="'.$value["id"].'">'.$value["name"].'</option>';
            }
            $this->assign('coup_str',$coup_str); 
        }

        /*查询出曾经转赠用户列表*/
        $userlist=M('give_log t0')->field('t1.head_pic,t1.nickname,t1.mobile')->join('tp_users t1','t0.give_user_id=t1.user_id','left')->where('t0.user_id',$this->user_id)->group('t0.give_user_id')->select();
        $this->assign('userlist',$userlist); 
        $this->assign('type',$type); 
        
        return $this->fetch();
     }
     public function do_give(){
        $type=I('post.type');
        $points=I('post.points');
        $coupon_id=I('post.coupon_id');
        $user_id=(int)I('post.user_id');
        $users=M('users');
        if( $type=="give_points"){
            $data['give_type']=0;//代表赠送积分
            $data['give_account']=$points;
            $pay_points=$users->where('user_id',$this->user_id)->getField('pay_points');
            if($pay_points<$points){
                echo "not_points";
                exit;
            }
             $is_vip=$users->where('user_id',$user_id)->getField('mobile');
             if($is_vip==null){
                echo "not_vip";
                exit;
             }
            $users->startTrans();
            $res1=accountLog($this->user_id,0,-$points,"转赠积分",0,"give_points");
            $res2=accountLog($user_id,0,$points,"转赠积分",0,"give_points");

            if($res1&&$res2){
                $users->commit();
                $result= 'success';
            }else{
                $users->rollback();
                $result= 'fail';
            }
        }
         if( $type=="give_coupon"){
             $data['give_type']=1;//代表赠送优惠券
             $data['give_account']=$coupon_id;
             $is_vip=$users->where(array('user_id'=>$user_id))->getField('mobile');
             if($is_vip==null){
                echo "not_vip";
                exit;
             }
            $res=M('coupon_list')->where(array('id'=>$coupon_id,'uid'=>$this->user_id))->save(array('uid'=>$user_id));
             if($res){
                 $result= 'success';
             }else{
                 $result= 'fail';
             }
         }

         $data['user_id']=$this->user_id;
         $data['give_user_id']=$user_id;
         $data['give_time']=time();
         M('give_log')->add($data);
         echo $result;

     }

     public function points_list()
     {
        $type = I('type', 'all');    //获取类型
        $this->assign('type', $type);
        if ($type == 'recharge') {
            //余额明细
            
            $count = M('account_log')->where('user_id='.$this->user_id.' and (user_money<>0)')->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where('user_id='.$this->user_id.' and (user_money<>0)')->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('title', '余额明细');
        } else if ($type == 'points') {
            //积分记录明细
            $count = M('account_log')->where(['user_id' => $this->user_id, 'pay_points' => ['<>', 0]])->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where(['user_id' => $this->user_id, 'pay_points' => ['<>', 0]])->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
            $this->assign('title', '积分记录明细');  
        } else {
            //全部
            $count = M('account_log')->where(['user_id' => $this->user_id, 'share_money' => ['<>', 0]])->count();
            $Page = new Page($count, 16);
            $account_log = M('account_log')->where(['user_id' => $this->user_id, 'share_money' => ['<>', 0]])->order('log_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
            $this->assign('title', '我的账单'); 
        }
        $showpage = $Page->show();
        $this->assign('account_log', $account_log);
        $this->assign('page', $showpage);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_points');
            exit;
        }
        return $this->fetch();
     }

    public function shopactive(){
        $num=I('post.num',1);
        if($num==1) 
            $shopactive=M('user_level')->select();
        if($num==2)
            $shopactive=M('user_level_distribution')->select();
        if($num==3){
            $shopactive=M('prom_goods')->where('end_time>='.time().' and is_close=0')->select();
            foreach ($shopactive as $key => $value) {
                if($value['type']=='0') $value['typename']="直接打折";
                if($value['type']=='1') $value['typename']="减价优惠";
                if($value['type']=='2') $value['typename']="固定金额出售";
                if($value['type']=='3') $value['typename']="买就赠代金券";
                if($value['start_time']>time()) {
                    $value['status']="未开始";
                }else{
                    $value['status']="进行中";
                }
                $shopactive[$key]=$value;
                    
            }
        }
        if($num==4){
            $shopactive=M('prom_order')->where('end_time>='.time().' and is_close=0')->select();
            foreach ($shopactive as $key => $value) {
                if($value['type']=='0') $value['typename']="直接打折";
                if($value['type']=='1') $value['typename']="减价优惠";
                if($value['type']=='2') $value['typename']="送积分";
                if($value['type']=='3') $value['typename']="买就赠代金券";
                if($value['start_time']>time()) {
                    $value['status']="未开始";
                }else{
                    $value['status']="进行中";
                }
                $shopactive[$key]=$value;
                    
            }
        }
        $this->assign('shopactive', $shopactive);
        $this->assign('num', $num);
        if(IS_AJAX){
            return $this->fetch('ajax_shopactive');
        }else{
            return $this->fetch();
        }
        
    }
    public function shopactive_detail(){
        $type=I('get.type');
        $id=I('get.id');
        if($type=='3')
            $typename=['直接打折','减价优惠','固定金额出售','买就赠代金券'];
            $proms=M('prom_goods')->where('id',$id)->find();
        if($type=='4')
            $typename=['直接打折','减价优惠','送积分','买就赠代金券'];
            $proms=M('prom_order')->where('id',$id)->find();
        $vips=M('user_level')->field('level_name')->where('level_id',array('in',$proms['group']))->select();
        foreach ($vips as $key => $value) {
            $vip[]=$value['level_name'];
        }
        $proms['type']=$typename[$proms['type']];
        $this->assign('proms', $proms);
        $this->assign('vips', implode(',', $vip));
         return $this->fetch();
    }


    public function logout()
    {
        session_unset();
        session_destroy();
        setcookie('cn', '', time() - 3600, '/');
        setcookie('user_id', '', time() - 3600, '/');
        //$this->success("退出成功",U('Mobile/Index/index'));
        header("Location:" . U('Mobile/Index/index'));
        exit();
    }

    /*
     * 账户资金
     */
    public function account()
    {
        $user = session('user');
        //获取账户资金记录
        $logic = new UsersLogic();
        $data = $logic->get_account_log($this->user_id, I('get.type'));
        $account_log = $data['result'];

        $this->assign('user', $user);
        $this->assign('account_log', $account_log);
        $this->assign('page', $data['show']);

        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_account_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 优惠券
     */
    public function coupon()
    {
        $logic = new UsersLogic();
        $data = $logic->get_coupon($this->user_id, input('type'));
        $coupon_list = $data['result'];
        $this->assign('coupon_list', $coupon_list);
        $this->assign('page', $data['show']);
        if (input('is_ajax')) {
            return $this->fetch('ajax_coupon_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 确定订单的使用优惠券
     * @author lxl
     * @time 2017
     */
    public function checkcoupon()
    {
        $cartLogic = new \app\home\logic\CartLogic();
        // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
        $result = $cartLogic->cartList($this->user, $this->session_id,1,1); // 获取购物车商品
        if(I('type') == ''){
            $where = " c2.uid = {$this->user_id} and ".time()." < c1.use_end_time and c1.condition <= {$result['total_price']['total_fee']} ";
        }
        if(I('type') == '1'){
           $where = " c2.uid = {$this->user_id} and c1.use_end_time < ".time()." or {$result['total_price']['total_fee']}  < c1.condition ";
        }

        $coupon_list = DB::name('coupon')
            ->alias('c1')
            ->field('c1.name,c1.money,c1.condition,c1.use_end_time, c2.*')
            ->join('coupon_list c2','c2.cid = c1.id and c1.type in(0,1,2,3) and order_id = 0','LEFT')
            ->where($where)
            ->select();
        $this->assign('coupon_list', $coupon_list); // 优惠券列表
        return $this->fetch();
    }

    public function ajaxCoupon(){
        $cid = I('id');
        if(empty($cid)){
            return 3;
        }
        $user_id = $this->user_id;
        $add['cid'] = $cid;
        $add['uid'] = $user_id;
        $add['type'] = '1';
        $add['send_time'] = time();
        $ccount=M('coupon_list')->where(array('cid'=>$cid,'uid'=>$user_id))->count();
        if($ccount>0){
            return 2;//已经领取优惠券
            exit;
        }
        if(M('coupon_list')->add($add)){
            return 1;
        }else{
            return 0;
        }
    }

public function getcoupon(){
        $cid = I('id');
        $user_id = $this->user_id;
        $ccount=M('coupon_list')->where(array('cid'=>$cid,'uid'=>$user_id))->count();
        $res=M('coupon')->where(array('id'=>$cid))->find();
        $this->assign('coupon',$res);
        $this->assign('ccount',$ccount);
        return $this->fetch();
}
    /**
     *  登录
     */
    public function login()
    {

        if ($this->user_id > 0) {
//
//            header("Location: " . U('Mobile/User/index'));
        }
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U("Mobile/User/index");
        $this->assign('referurl', $referurl);

        return $this->fetch();
    }

    /**
     * 登录
     */
    public function do_login()
    {
        $username = I('post.username');
        $password = I('post.password');
        $username = trim($username);
        $password = trim($password);
        //验证码验证
        $verify_code = I('post.verify_code');
        $verify = new Verify();
        if (!$verify->check($verify_code, 'user_login')) {
            $res = array('status' => 0, 'msg' => '验证码错误');
            exit(json_encode($res));
        }
        $logic = new UsersLogic();
        $res = $logic->login($username, $password);
        if ($res['status'] == 1) {
            $res['url'] = urldecode(I('post.referurl'));
            session('user', $res['result']);
            setcookie('user_id', $res['result']['user_id'], null, '/');
            setcookie('is_distribut', $res['result']['is_distribut'], null, '/');
            $nickname = empty($res['result']['nickname']) ? $username : $res['result']['nickname'];
            setcookie('uname', $nickname, null, '/');
            setcookie('cn', 0, time() - 3600, '/');
            $cartLogic = new \app\home\logic\CartLogic();
            $cartLogic->login_cart_handle($this->session_id, $res['result']['user_id']);  //用户登录后 需要对购物车 一些操作
        }

        exit(json_encode($res));
    }

    /**
     *  注册
     */
    public function reg()
    {

    	if($this->user_id > 0) header("Location: ".U('Mobile/User/index'));
        $reg_sms_enable = tpCache('sms.regis_sms_enable');
        $reg_smtp_enable = tpCache('sms.regis_smtp_enable');

        if (IS_POST) {
            $logic = new UsersLogic();
            //验证码检验
            //$this->verifyHandle('user_reg');
            $username = I('post.username', '');
            $password = I('post.password', '');
            $password2 = I('post.password2', '');
            //是否开启注册验证码机制
            $code = I('post.mobile_code', '');
            $scene = I('post.scene', 1);

            $session_id = session_id();

            if(check_mobile($username)){
                $check_code = $logic->check_validate_code($code, $username, 'phone', $session_id , $scene);
                if($check_code['status'] != 1){
                    $this->error($check_code['msg']);
                }
            }
            //是否开启注册邮箱验证码机制
            if(check_email($username)){
                $check_code = $logic->check_validate_code($code, $username);
                if($check_code['status'] != 1){
                    $this->error($check_code['msg']);
                }
            }

            $data = $logic->reg($username, $password, $password2);
            if ($data['status'] != 1)
                $this->error($data['msg']);
            session('user', $data['result']);
            setcookie('user_id', $data['result']['user_id'], null, '/');
            setcookie('is_distribut', $data['result']['is_distribut'], null, '/');
            $cartLogic = new \app\home\logic\CartLogic();
            $cartLogic->login_cart_handle($this->session_id, $data['result']['user_id']);  //用户登录后 需要对购物车 一些操作
            $this->success($data['msg'], U('Mobile/User/index'));
            exit;
        }
        $this->assign('regis_sms_enable',$reg_sms_enable); // 注册启用短信：
        $this->assign('regis_smtp_enable',$reg_smtp_enable); // 注册启用邮箱：
        $sms_time_out = tpCache('sms.sms_time_out')>0 ? tpCache('sms.sms_time_out') : 120;
        $this->assign('sms_time_out', $sms_time_out); // 手机短信超时时间
        return $this->fetch();
    }

    /*
     * 订单列表
     */
    public function order_list()
    {
        $where = ' user_id=' . $this->user_id;
        //条件搜索
       if(I('get.type')){
            $where .= C(strtoupper(I('get.type')));
       }
        $count = M('order')->where($where)->count();
        $Page = new Page($count, 10);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();

        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
        }
        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = '';
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
        }

        $this->assign('order_status', C('ORDER_STATUS'));
        $this->assign('shipping_status', C('SHIPPING_STATUS'));
        $this->assign('pay_status', C('PAY_STATUS'));
        $this->assign('page', $show);
        $this->assign('lists', $order_list);

        $this->assign('active', 'order_list');
        $this->assign('active_status', I('get.type'));
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_order_list');
            exit;
        }
        return $this->fetch();
    }


    /*
     * 订单列表
     */
    public function ajax_order_list()
    {

    }

    /*
     * 订单详情
     */
    public function order_detail()
    {
        $id = I('get.id/d');
        $map['order_id'] = $id;
        $map['user_id'] = $this->user_id;
        $order_info = M('order')->where($map)->find();
        $order_info = set_btn_order_status($order_info);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
        if (!$order_info) {
            $this->error('没有获取到订单信息');
            exit;
        }
        //获取订单商品
        $model = new UsersLogic();
        $data = $model->get_order_goodslist($order_info['order_id']);
        $order_info['goods_list'] = $data['result'];
        //var_dump($order_info);

        //$order_info['total_fee'] = $order_info['goods_price'] + $order_info['shipping_price'] - $order_info['integral_money'] -$order_info['coupon_price'] - $order_info['discount'];

        $region_list = get_region_list();
        $invoice_no = M('DeliveryDoc')->where("order_id", $id)->getField('invoice_no', true);
        $order_info[invoice_no] = implode(' , ', $invoice_no);
        //获取订单操作记录
        $order_action = M('order_action')->where(array('order_id' => $id))->select();
        $this->assign('order_status', C('ORDER_STATUS'));
        $this->assign('shipping_status', C('SHIPPING_STATUS'));
        $this->assign('pay_status', C('PAY_STATUS'));
        $this->assign('region_list', $region_list);
        $this->assign('order_info', $order_info);
        $this->assign('order_action', $order_action);

        if (I('waitreceive')) {  //待收货详情
            return $this->fetch('wait_receive_detail');
        }
        return $this->fetch();
    }

    public function express()
    {
        $order_id = I('get.order_id/d', 195);
        $order_goods = M('order_goods')->where("order_id", $order_id)->select();
        $delivery = M('delivery_doc')->where("order_id", $order_id)->find();
        $this->assign('order_goods', $order_goods);
        $this->assign('delivery', $delivery);
        return $this->fetch();
    }

    /*
     * 取消订单
     */
    public function cancel_order()
    {
        $id = I('get.id/d');
        //检查是否有积分，余额支付
        $logic = new UsersLogic();
        $data = $logic->cancel_order($this->user_id, $id);
        if ($data['status'] < 0)
            $this->error($data['msg']);
        $this->success($data['msg']);
    }





    /*
     * 用户地址列表
     */
    public function address_list()
    {
        $address_lists = get_user_address_list($this->user_id);
        $region_list = get_region_list();
        $this->assign('region_list', $region_list);
        $this->assign('lists', $address_lists);
        return $this->fetch();
    }

    /*
     * 添加地址
     */
    public function add_address()
    {
        if (IS_POST) {
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, 0, I('post.'));
            if ($data['status'] != 1)
                $this->error($data['msg']);
            elseif (I('post.source') == 'cart2') {
                header('Location:' . U('/Mobile/Cart/cart2', array('address_id' => $data['result'])));
                exit;
            }

            $this->success($data['msg'], U('/Mobile/User/address_list'));
            exit();
        }
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $this->assign('province', $p);
        //return $this->fetch('edit_address');
        return $this->fetch();

    }

    /*
     * 地址编辑
     */
    public function edit_address()
    {
        $id = I('id/d');
        $address = M('user_address')->where(array('address_id' => $id, 'user_id' => $this->user_id))->find();
        if (IS_POST) {
            $logic = new UsersLogic();
            $data = $logic->add_address($this->user_id, $id, I('post.'));
            if ($_POST['source'] == 'cart2') {
                header('Location:' . U('/Mobile/Cart/cart2', array('address_id' => $id)));
                exit;
            } else
                $this->success($data['msg'], U('/Mobile/User/address_list'));
            exit();
        }
        //获取省份
        $p = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $c = M('region')->where(array('parent_id' => $address['province'], 'level' => 2))->select();
        $d = M('region')->where(array('parent_id' => $address['city'], 'level' => 3))->select();
        if ($address['twon']) {
            $e = M('region')->where(array('parent_id' => $address['district'], 'level' => 4))->select();
            $this->assign('twon', $e);
        }
        $this->assign('province', $p);
        $this->assign('city', $c);
        $this->assign('district', $d);
        $this->assign('address', $address);
        return $this->fetch();
    }

    /*
     * 设置默认收货地址
     */
    public function set_default()
    {
        $id = I('get.id/d');
        $source = I('get.source');
        M('user_address')->where(array('user_id' => $this->user_id))->save(array('is_default' => 0));
        $row = M('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->save(array('is_default' => 1));
        if ($source == 'cart2') {
           // header("Location:". U('Mobile/Cart/cart2'));
             $this->redirect(U('Mobile/Cart/cart2'),1);
            exit;
        } else {
            $this->redirect(U('Mobile/User/address_list'),1);
        }
    }

    /*
     * 地址删除
     */
    public function del_address()
    {
        $id = I('get.id/d');

        $address = M('user_address')->where("address_id", $id)->find();
        $row = M('user_address')->where(array('user_id' => $this->user_id, 'address_id' => $id))->delete();
        // 如果删除的是默认收货地址 则要把第一个地址设置为默认收货地址
        if ($address['is_default'] == 1) {
            $address2 = M('user_address')->where("user_id", $this->user_id)->find();
            $address2 && M('user_address')->where("address_id", $address2['address_id'])->save(array('is_default' => 1));
        }
        if (!$row)
            $this->error('操作失败', U('User/address_list'));
        else
            $this->success("操作成功", U('User/address_list'));
    }

    /*
     * 评论晒单
     */
    public function comment()
    {
        $user_id = $this->user_id;
        $status = I('get.status');
        $logic = new UsersLogic();
        $result = $logic->get_comment($user_id, $status); //获取评论列表
        $this->assign('comment_list', $result['result']);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_comment_list');
            exit;
        }
        return $this->fetch();
    }

    /*
     *添加评论
     */
    public function add_comment()
    {
        if (IS_POST) {
            // 晒图片
            $files = request()->file('comment_img_file');
            $save_url = 'public/upload/comment/' . date('Y', time()) . '/' . date('m-d', time());
            foreach ($files as $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->rule('uniqid')->validate(['size' => 1024 * 1024 * 3, 'ext' => 'jpg,png,gif,jpeg'])->move($save_url);
                if ($info) {
                    // 成功上传后 获取上传信息
                    // 输出 jpg
                    $comment_img[] = '/'.$save_url . '/' . $info->getFilename();
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            }
            if (!empty($comment_img)) {
                $add['img'] = serialize($comment_img);
            }

            $user_info = session('user');
            $logic = new UsersLogic();
            $add['goods_id'] = I('goods_id/d');
            $add['email'] = $user_info['email'];
            $hide_username = I('hide_username');
            if (empty($hide_username)) {
                $add['username'] = $user_info['nickname'];
            }
            $add['order_id'] = I('order_id/d');
            $add['service_rank'] = I('service_rank');
            $add['deliver_rank'] = I('deliver_rank');
            $add['goods_rank'] = I('goods_rank');
            $add['is'] = I('goods_rank');
            //$add['content'] = htmlspecialchars(I('post.content'));
            $add['content'] = I('content');
            $add['add_time'] = time();
            $add['ip_address'] = getIP();
            $add['user_id'] = $this->user_id;
            $add['is_show'] = 1;

            //添加评论
            $row = $logic->add_comment($add);
            if ($row['status'] == 1) {
                $this->success('评论成功', U('/Mobile/Goods/goodsInfo', array('id' => $add['goods_id'])));
                exit();
            } else {
                $this->error($row['msg']);
            }
        }
        $rec_id = I('rec_id/d');
        $order_goods = M('order_goods')->where("rec_id", $rec_id)->find();
        $this->assign('order_goods', $order_goods);
        return $this->fetch();
    }

    /*
     * 个人信息
     */
    public function userinfo()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        if (IS_POST) {
            I('post.nickname') ? $post['nickname'] =base64_encode(I('post.nickname')) : false; //昵称
            I('post.qq') ? $post['qq'] = I('post.qq') : false;  //QQ号码
            I('post.head_pic') ? $post['head_pic'] = I('post.head_pic') : false; //头像地址
            I('post.sex') ? $post['sex'] = I('post.sex') : $post['sex'] = 0;  // 性别
            I('post.birthday') ? $post['birthday'] = strtotime(I('post.birthday')) : false;  // 生日
            I('post.province') ? $post['province'] = I('post.province') : false;  //省份
            I('post.city') ? $post['city'] = I('post.city') : false;  // 城市
            I('post.district') ? $post['district'] = I('post.district') : false;  //地区
            I('post.email') ? $post['email'] = I('post.email') : false; //邮箱
            I('post.mobile') ? $post['mobile'] = I('post.mobile') : false; //手机

            $email = I('post.email');
            $mobile = I('post.mobile');
            $code = I('post.mobile_code', '');
            $scene = I('post.scene', 6);

            $post['work'] = I('post.work');
            $post['is_marry'] = I('post.is_marry');
            $post['income'] = I('post.income');
            $post['dressing_style'] = I('post.dressing_style');
            $post['upper_size'] = I('post.upper_size');
            $post['trousers_size'] = I('post.trousers_size');
            $post['shose_size'] = I('post.shose_size');

            $post['reg_time']=time();

            if (!empty($email)) {
                $c = M('users')->where(['email' => input('post.email'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("邮箱已被使用");
            }
            if (empty($post['work'])) {
                $this->error("职业不能为空");
            }
            if (!empty($mobile)) {
                $c = M('users')->where(['mobile' => input('post.mobile'), 'user_id' => ['<>', $this->user_id]])->count();
                $c && $this->error("手机已被使用");
                if (!$code)
                    $this->error('请输入验证码');
                $check_code = $userLogic->check_validate_code($code, $mobile, 'phone', $this->session_id, $scene);
                if ($check_code['status'] != 1)
                    $this->error($check_code['msg']);
            }

            if (!$userLogic->update_info($this->user_id, $post))
            $this->error("保存失败");
            //如果是第一次绑定会员，送优惠券、积分
            if(empty($user_info['mobile'])){
                $pay_points = tpCache('basic.reg_integral'); // 会员注册赠送积分
                if($pay_points > 0)
                    update_user_level($this->user_id);
                    accountLog($this->user_id, 0,$pay_points, '会员注册赠送积分',0,'reg'); // 记录日志流水
                    // 会员注册送优惠券
                    $coupon = M('coupon')->where("send_end_time > ".time()." and ((createnum - send_num) > 0 or createnum = 0) and type = 2")->select();
                    foreach ($coupon as $key => $val)
                    {
                        // 送券            
                        M('coupon_list')->add(array('cid'=>$val['id'],'type'=>$val['type'],'uid'=>$this->user_id,'send_time'=>time()));
                        M('Coupon')->where("id", $val['id'])->setInc('send_num'); // 优惠券领取数量加一
                        $tplarr=array(
                            'title'=>'您有一张'.$val['name'].'注意查收',
                            'description'=>'有效期：'.date('Y-m-d',$val['use_start_time']).'~'.date('Y-m-d',$val['use_end_time']),
                            'url'=>$val['coupon_url'],
                            'picurl'=>$val['coupon_picurl'],
                            );
                        push_wxmessage($this->user_id,$tplarr,'news');
                    }
            }
            
            $this->success("操作成功");
            exit;
        }
        //  获取省份
       // $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        //  获取订单城市
       // $city = M('region')->where(array('parent_id' => $user_info['province'], 'level' => 2))->select();
        //  获取订单地区
        //$area = M('region')->where(array('parent_id' => $user_info['city'], 'level' => 3))->select();
        //获取会员属性信息
        $user_attr=M("users_attribute")->where(['is_show'=>1])->select();

        foreach ($user_attr as $key => $value) {
            if($value['attr_name']=="职业"){
                $work=explode(',',$value['attr_values']);
            }
            if($value['attr_name']=="收入"){
                $income=explode(',',$value['attr_values']);
            }
            if($value['attr_name']=="穿衣风格"){
                $dress_style=explode(',',$value['attr_values']);
            }
            if($value['attr_name']=="上衣尺码"){
                $upper_size=explode(',',$value['attr_values']);
            }
            if($value['attr_name']=="裤子尺码"){
                $trousers_size=explode(',',$value['attr_values']);
            }
            if($value['attr_name']=="鞋品尺码"){
                $shose_size=explode(',',$value['attr_values']);
            }
        }
        $this->assign('work', $work);
        $this->assign('income', $income);
        $this->assign('dress_style', $dress_style);
        $this->assign('upper_size', $upper_size);
        $this->assign('trousers_size', $trousers_size);
        $this->assign('shose_size', $shose_size);
        $this->assign('user', $user_info);
        $this->assign('sex', C('SEX'));
        //从哪个修改用户信息页面进来，
        $dispaly = I('action');
        if ($dispaly != '') {
            return $this->fetch("$dispaly");
            exit;
        }
        return $this->fetch();
    }


    //赋值生成的付款码到SEESION
    public function mycode(){
           $userinfo=$this->user;
           $codestr=$userinfo['mobile'];
           $level_name = M('user_level')->where("level_id", $userinfo['level'])->getField('level_name'); // 等级名称
           session('codestr',$codestr);
           //将会员信息更新到道讯数据库
           $UsersLogic=new UsersLogic();
           $UsersLogic->run_storedprocedure($userinfo['mobile'],$userinfo['birthday'],$userinfo['level']);
           $this->assign('level_name', $level_name);
           return $this->fetch();
       }
    //输出条形码
    public function bgscode(){
        bgcode(session('codestr'));
    }

    //输出二维码
    public function qrscode(){
        qrcode(session('codestr'));
    }

    /*
     * 邮箱验证
     */
    public function email_validate()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('get.step', 1);
        //验证是否未绑定过
        if ($user_info['email_validated'] == 0)
            $step = 2;
        //原邮箱验证是否通过
        if ($user_info['email_validated'] == 1 && session('email_step1') == 1)
            $step = 2;
        if ($user_info['email_validated'] == 1 && session('email_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $email = I('post.email');
            $code = I('post.code');
            $info = session('email_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $email || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('email_code', null);
                    session('email_step1', null);
                    if (!$userLogic->update_email_mobile($email, $this->user_id))
                        $this->error('邮箱已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                } else {
                    session('email_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/email_validate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码邮箱不匹配');
        }
        $this->assign('step', $step);
        return $this->fetch();
    }

    /*
    * 手机验证
    */
    public function mobile_validate()
    {
        $userLogic = new UsersLogic();
        $user_info = $userLogic->get_info($this->user_id); // 获取用户信息
        $user_info = $user_info['result'];
        $step = I('get.step', 1);
        //验证是否未绑定过
        if ($user_info['mobile_validated'] == 0)
            $step = 2;
        //原手机验证是否通过
        if ($user_info['mobile_validated'] == 1 && session('mobile_step1') == 1)
            $step = 2;
        if ($user_info['mobile_validated'] == 1 && session('mobile_step1') != 1)
            $step = 1;
        if (IS_POST) {
            $mobile = I('post.mobile');
            $code = I('post.code');
            $info = session('mobile_code');
            if (!$info)
                $this->error('非法操作');
            if ($info['email'] == $mobile || $info['code'] == $code) {
                if ($user_info['email_validated'] == 0 || session('email_step1') == 1) {
                    session('mobile_code', null);
                    session('mobile_step1', null);
                    if (!$userLogic->update_email_mobile($mobile, $this->user_id, 2))
                        $this->error('手机已存在');
                    $this->success('绑定成功', U('Home/User/index'));
                } else {
                    session('mobile_code', null);
                    session('email_step1', 1);
                    redirect(U('Home/User/mobile_validate', array('step' => 2)));
                }
                exit;
            }
            $this->error('验证码手机不匹配');
        }
        $this->assign('step', $step);
        return $this->fetch();
    }

    /**
     * 用户收藏列表
     */
    public function collect_list()
    {
        $userLogic = new UsersLogic();
        $data = $userLogic->get_goods_collect($this->user_id);
        $this->assign('page', $data['show']);// 赋值分页输出
        $this->assign('goods_list', $data['result']);
        if (IS_AJAX) {      //ajax加载更多
            return $this->fetch('ajax_collect_list');
            exit;
        }
        return $this->fetch();
    }

    /*
     *取消收藏
     */
    public function cancel_collect()
    {
        $collect_id = I('collect_id/d');
        $user_id = $this->user_id;
        if (M('goods_collect')->where(['collect_id' => $collect_id, 'user_id' => $user_id])->delete()) {
            $this->success("取消收藏成功", U('User/collect_list'));
        } else {
            $this->error("取消收藏失败", U('User/collect_list'));
        }
    }

    /**
     * 我的留言
     */
    public function message_list()
    {
        C('TOKEN_ON', true);
        if (IS_POST) {
            $this->verifyHandle('message');

            $data = I('post.');
            $data['user_id'] = $this->user_id;
            $user = session('user');
            $data['user_name'] = $user['nickname'];
            $data['msg_time'] = time();
            if (M('feedback')->add($data)) {
                $this->success("留言成功", U('User/message_list'));
                exit;
            } else {
                $this->error('留言失败', U('User/message_list'));
                exit;
            }
        }
        $msg_type = array(0 => '留言', 1 => '投诉', 2 => '询问', 3 => '售后', 4 => '求购');
        $count = M('feedback')->where("user_id", $this->user_id)->count();
        $Page = new Page($count, 100);
        $Page->rollPage = 2;
        $message = M('feedback')->where("user_id", $this->user_id)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $showpage = $Page->show();
        header("Content-type:text/html;charset=utf-8");
        $this->assign('page', $showpage);
        $this->assign('message', $message);
        $this->assign('msg_type', $msg_type);
        return $this->fetch();
    }

 
    public function points()
    {
        
        return $this->fetch();
    }
     public function give_points()
    {
        
        return $this->fetch();
    }

    /*
     * 密码修改
     */
    public function password()
    {
        //检查是否第三方登录用户
        $logic = new UsersLogic();
        $data = $logic->get_info($this->user_id);
        $user = $data['result'];
        if ($user['mobile'] == '' && $user['email'] == '')
            $this->error('请先到电脑端绑定手机', U('/Mobile/User/index'));
        if (IS_POST) {
            $userLogic = new UsersLogic();
            $data = $userLogic->password($this->user_id, I('post.old_password'), I('post.new_password'), I('post.confirm_password')); // 获取用户信息
            if ($data['status'] == -1)
                $this->error($data['msg']);
            $this->success($data['msg']);
            exit;
        }
        return $this->fetch();
    }

    function forget_pwd()
    {
        if ($this->user_id > 0) {
            $this->redirect("User/index");
//            header("Location: " . U('User/Index'));`
        }
        $username = I('username');
        if (IS_POST) {
            if (!empty($username)) {
                $this->verifyHandle('forget');
                $field = 'mobile';
                if (check_email($username)) {
                    $field = 'email';
                }
                $user = M('users')->where("email", $username)->whereOr('mobile', $username)->find();
                if ($user) {
                    session('find_password', array('user_id' => $user['user_id'], 'username' => $username,
                        'email' => $user['email'], 'mobile' => $user['mobile'], 'type' => $field));
                    header("Location: " . U('User/find_pwd'));
                    exit;
                } else {
                    $this->error("用户名不存在，请检查");
                }
            }
        }
        return $this->fetch();
    }

    function find_pwd()
    {
        if ($this->user_id > 0) {
            header("Location: " . U('User/index'));
        }
        $user = session('find_password');
        if (empty($user)) {
            $this->error("请先验证用户名", U('User/forget_pwd'));
        }
        $this->assign('user', $user);
        return $this->fetch();
    }


    public function set_pwd()
    {
        if ($this->user_id > 0) {
//            header("Location: " . U('User/Index'));
            $this->redirect('Mobile/User/index');
        }
        $check = session('validate_code');
        if (empty($check)) {
            header("Location:" . U('User/forget_pwd'));
        } elseif ($check['is_check'] == 0) {
            $this->error('验证码还未验证通过', U('User/forget_pwd'));
        }
        if (IS_POST) {
            $password = I('post.password');
            $password2 = I('post.password2');
            if ($password2 != $password) {
                $this->error('两次密码不一致', U('User/forget_pwd'));
            }
            if ($check['is_check'] == 1) {
                //$user = get_user_info($check['sender'],1);
                $user = M('users')->where("mobile", $check['sender'])->whereOr('email', $check['sender'])->find();
                M('users')->where("user_id", $user['user_id'])->save(array('password' => encrypt($password)));
                session('validate_code', null);
                //header("Location:".U('User/set_pwd',array('is_set'=>1)));
                $this->success('新密码已设置行牢记新密码', U('User/index'));
                exit;
            } else {
                $this->error('验证码还未验证通过', U('User/forget_pwd'));
            }
        }
        $is_set = I('is_set', 0);
        $this->assign('is_set', $is_set);
        return $this->fetch();
    }

    /**
     * 验证码验证
     * $id 验证码标示
     */
    private function verifyHandle($id)
    {
        $verify = new Verify();
        if (!$verify->check(I('post.verify_code'), $id ? $id : 'user_login')) {
            $this->error("验证码错误");
        }
    }

    /**
     * 验证码获取
     */
    public function verify()
    {
        //验证码类型
        $type = I('get.type') ? I('get.type') : 'user_login';
        $config = array(
            'fontSize' => 40,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
        );
        $Verify = new Verify($config);
        $Verify->entry($type);
    }

    /**
     * 账户管理
     */
    public function accountManage()
    {
        return $this->fetch();
    }

    /**
     * 确认收货成功
     */
    public function order_confirm()
    {
        $id = I('get.id/d', 0);
        $data = confirm_order($id, $this->user_id);
        
//        $data['status'] = '1';
        if ($data['status']<0) {
            $this->error($data['msg']);
        } else {
            $user_id = get_user_id();
            $user_level = M('user_level_distribution')->order('level_id')->select();
            $goodid = array();
            $goodname='';
            //分销反余额
            $orderList = M('order_goods')->field('rec_id,goods_id,goods_name,order_id,goods_price,member_goods_price,goods_num')->where('order_id = '.$id)->select();
            foreach($orderList as $k=>$v){
                $goodid[] = $v['goods_id'];
                $goodname.= '【'.$v['goods_name'].'】';
            }

            $goods_id = implode(',',$goodid);
            $where['s_user_id'] = $user_id['user_id'];
            $where['goods_id'] = array('in',$goods_id);
            $share = M('share_record')->where($where)->select();
            $agents=M('agents')->where('agent_id',$this->weixin_config['agent_id'])->find();
            if($agents['parent_id']>0){
                $parent_agent=M('agents')->where('agent_id',$agents['parent_id'])->find();
            }

            if($share) {
                foreach ($share as $k => $v) {
                    if (empty($v['s_id'])) {
                        $share_user = M('users')->where('user_id = ' . $v['user_id'])->find();
                        $level = M('user_level_distribution')->where(array('level_id' => $share_user['profit_level']))->find();

                        if($level){
                            //$distributCount = $level['discount_one'] + $level['discount_two'];
                            $distributCount = $level['discount_one'];
                            $goods = M('order_goods')->field('rec_id,member_goods_price,goods_price,goods_num,goods_name,order_id')->where('order_id = ' . $id . ' and goods_id = ' . $v['goods_id'])->find();
                            $order = M('order')->field('order_id,order_sn')->where('order_id',$goods['order_id'])->find();
                            if(tpCache('shopping.restand')==1){
                                $goodsprice=$goods['goods_price'];
                            }elseif(tpCache('shopping.restand')==2){
                                $goodsprice=$goods['member_goods_price'];
                            }
                            $money = ($goodsprice * $distributCount) * $goods['goods_num'];
                            $money = $money / 100;
                            
                            if($agents&&$agents['is_check']>0){
                                //计算代理商收入金额
                                $agent_discount=M('agents a')->join('agent_level b','a.level_id=b.level_id','left')->where(['a.agent_id'=>$agents['agent_id']])->getField('discount');
                               
                                $good_price=$goods['goods_price']*$agent_discount/100;
                                $agent_money=bcsub($goods['member_goods_price'],$good_price,2)*$goods['goods_num'];
                                $agent_moneys[]=array('agent_id'=>$agents['agent_id'],'money'=>bcsub($agent_money,$money,2));
                            }
                            if($parent_agent&&$parent_agent['is_check']>0){
                                //计算父级代理商收入金额
                                $parent_discount=M('agents a')->join('agent_level b','a.level_id=b.level_id','left')->where(['a.agent_id'=>$parent_agent['agent_id']])->getField('discount');
                                $agent_money=$goods['goods_price']*$goods['goods_num']*($agent_discount-$parent_discount)/100;
                                $agent_moneys[]=array('agent_id'=>$parent_agent['agent_id'],'money'=>$agent_money);
                                
                            }
                            
                            //如果没有s_id，则返回商品价格的10%
                            $add['user_id'] = $v['user_id'];
                            $add['share_money'] = $money;
                            $add['change_time'] = time();
                            $add['desc'] = "一级分销返回" . ($money) . "余额";
                            $add['order_sn'] = $order['order_sn'];
                            $add['order_id'] = $order['order_id'];
                            $acc_re = M('account_log')->add($add);
                            
                            if (!$acc_re) {
                                $this->error('分销反额记录失败');
                            }
                            $user_re = M('users')->where('user_id = ' . $v['user_id'])->save(array("distribut_money" => array("exp", "distribut_money+" . $money), "profit_amount" => array("exp", "profit_amount+" . $money)));
                            if (!$user_re) {
                                $this->error('余额充值错误');
                            }
                            $userFind = M('users')->field('profit_level,profit_amount')->where('user_id = ' . $v['user_id'])->find();
                            foreach ($user_level as $key => $val){
                                if ($userFind['profit_amount'] >= $val['amount']) {
                                    $level = $user_level[$key]['level_id'];
                                }
                            }
                            //累计额度达到新等级，更新会员折扣
                            if (isset($level) && $level > $userFind['profit_level']) {
                                $updata['profit_level'] = $level;
                                M('users')->where("user_id", $v['user_id'])->save($updata);
                            }
                            //发送微信消息
                            // 如果有微信公众号 则推送一条消息到微信
                            $wx_content = '恭喜您：你的一级分销商' . shownickname($user_id['nickname']) . '，购买了您分享的商品【' . $goods['goods_name'] . '】，你所分得的收益为：' . $money . '元。';
                            $wx_tplarr=array (
                                'first' => 
                                array (
                                  'value' => '恭喜您：你的一级分销商' . shownickname($user_id['nickname']).'已购买了您分享的商品哦',
                                  'color' => '#333',
                                ),
                                'keyword1' => 
                                array (
                                  'value' => '【' . $goods['goods_name'] . '】',
                                  'color' => '#333',
                                ),
                                'keyword2' => 
                                array (
                                  'value' =>  $money ,
                                  'color' => '#333',
                                ),
                                'keyword3' => 
                                array (
                                  'value' => '已确认收货' ,
                                  'color' => '#333',
                                ),
                                'remark' => 
                                array (
                                  'value' => '感谢您的参与，你随时可以在可用余额中提取您的佣金！',
                                  'color' => '#333',
                                )
                             );
                             $url='/mobile/User/points/type/all.html';
                             //push_wxmessage($v['user_id'], $wx_content);
                             push_wxtplmessage($v['user_id'],$wx_tplarr,$url,'distribut');
                        }
                    } else {
                        //一级分销，返回一级
                        $goods = M('order_goods')->field('member_goods_price,goods_price,goods_num,goods_name,order_id,rec_id')->where('order_id = ' . $id . ' and goods_id = ' . $v['goods_id'])->find();
                        if(tpCache('shopping.restand')==1){
                            $goodsprice=$goods['goods_price'];
                        }elseif(tpCache('shopping.restand')==2){
                            $goodsprice=$goods['member_goods_price'];
                        }
                        $order = M('order')->field('order_id,order_sn')->where('order_id',$goods['order_id'])->find();
                        $share_user_one = M('users')->where('user_id = ' . $v['user_id'])->find();
                        $level_one = M('user_level_distribution')->where(array('level_id' => $share_user_one['profit_level']))->find();
                        $money_one = ($goodsprice * $level_one['discount_one']) * $goods['goods_num'];
                        $money_one = $money_one / 100;
                        //有s_id，返回第一级的为7%；
                        $add_one['user_id'] = $v['user_id'];
                        $add_one['share_money'] = $money_one;
                        $add_one['change_time'] = time();
                        $add_one['desc'] = "分销一级返回" . ($money_one) . "余额";
                        $add_one['order_sn'] = $order['order_sn'];
                        $add_one['order_id'] = $order['order_id'];
                        $acc_re_one = M('account_log')->add($add_one);

                        if (!$acc_re_one) {
                            $this->error('一级分销反额记录失败');
                        }
                        $user_re_one = M('users')->where('user_id = ' . $v['user_id'])->save(array("distribut_money" => array("exp", "distribut_money+" . $money_one), "profit_amount" => array("exp", "profit_amount+" . $money_one)));
                        if (!$user_re_one) {
                            $this->error('一级分销余额充值错误');
                        }
                        $userFindOne = M('users')->field('profit_level,profit_amount')->where('user_id = ' . $v['user_id'])->find();
                        foreach ($user_level as $key => $val) {
                            if ($userFindOne['profit_amount'] >= $val['amount']) {
                                $levelOne = $user_level[$key]['level_id'];
                            }
                        }
                        //累计额度达到新等级，更新会员折扣
                        if (isset($levelOne) && $levelOne > $userFindOne['profit_level']) {
                            $updataOne['profit_level'] = $levelOne;
                            M('users')->where("user_id", $v['user_id'])->save($updataOne);
                        }
                        // 如果有微信公众号 则推送一条消息到微信
                        $wx_content = '恭喜您：你的一级分销商' . shownickname($user_id['nickname']) . '，购买了您分享的商品【' . $goods['goods_name'] . '】，你所分得的收益为：' . $money_one . '元。';
                        $wx_tplarr1=array (
                            'first' => 
                            array (
                              'value' => '恭喜您：你的一级分销商' . shownickname($user_id['nickname']).'已购买了您分享的商品哦',
                              'color' => '#333',
                            ),
                            'keyword1' => 
                            array (
                              'value' => '【' . $goods['goods_name'] . '】',
                              'color' => '#333',
                            ),
                            'keyword2' => 
                            array (
                              'value' =>  $money_one ,
                              'color' => '#333',
                            ),
                            'keyword3' => 
                            array (
                              'value' => '已确认收货' ,
                              'color' => '#333',
                            ),
                            'remark' => 
                            array (
                              'value' => '感谢您的参与，你随时可以在可用余额中提取您的佣金！',
                              'color' => '#333',
                            )
                         );
                         $url='/mobile/User/points/type/all.html';
                       // push_wxmessage($v['user_id'], $wx_content);
                        push_wxtplmessage($v['user_id'],$wx_tplarr1,$url,'distribut');


                        //返回为3%
                        $user_two = M('share_record')->find($v['s_id']);
                        $share_user_two = M('users')->where('user_id = '. $user_two['user_id'])->find();
                        $level_two = M('user_level_distribution')->where(array('level_id' => $share_user_two['profit_level']))->find();

                        $money_two = ($goodsprice * $level_two['discount_two']) * $goods['goods_num'];
                        $money_two = $money_two / 100;
                        $share_two = M('share_record')->find($v['s_id']);
                        $add_two['user_id'] = $share_two['user_id'];
                        $add_two['share_money'] = $money_two;
                        $add_two['change_time'] = time();
                        $add_two['desc'] = "分销二级返回" . ($money_two) . "余额";
                        $add_two['order_sn'] = $order['order_sn'];
                        $add_two['order_id'] = $order['order_id'];
                        $acc_re_two = M('account_log')->add($add_two);
                        if (!$acc_re_two) {
                            $this->error('二级分销反额记录失败');
                        }

                        if($agents&&$agents['is_check']>0){
                             //计算代理商收入金额
                            $agent_discount=M('agents a')->join('agent_level b','a.level_id=b.level_id','left')->where(['a.agent_id'=>$agents['agent_id']])->getField('discount');
                            $good_price=$goods['goods_price']*$agent_discount/100;
                            $agent_money=bcsub($goods['member_goods_price'],$good_price,2)*$goods['goods_num'];
                            $agent_money=bcsub($agent_money,$money_one,2);
                            $agent_money=bcsub($agent_money,$money_two,2);
                            $agent_moneys[]=array('agent_id'=>$agents['agent_id'],'money'=>$agent_money);
                        }
                       
                        if($parent_agent&&$parent_agent['is_check']>0){
                            //计算父级代理商收入金额
                            $parent_discount=M('agents a')->join('agent_level b','a.level_id=b.level_id','left')->where(['a.agent_id'=>$parent_agent['agent_id']])->getField('discount');
                            $agent_money=$goods['goods_price']*$goods['goods_num']*($agent_discount-$parent_discount)/100;
                            $agent_moneys[]=array('agent_id'=>$parent_agent['agent_id'],'money'=>$agent_money);
                        }

                        $user_re_two = M('users')->where('user_id = ' . $share_two['user_id'])->save(array("distribut_money" => array("exp", "distribut_money+" . $money_two), "profit_amount" => array("exp", "profit_amount+" . $money_two)));
                        if (!$user_re_two) {
                            $this->error('二级分销余额充值错误');
                        }
                        $userFindTwo = M('users')->field('profit_level,profit_amount')->where('user_id = ' . $share_two['user_id'])->find();
                        foreach ($user_level as $key => $val) {
                            if ($userFindTwo['profit_amount'] >= $val['amount']) {
                                $levelTwo = $user_level[$key]['level_id'];
                            }
                        }
                        //累计额度达到新等级，更新会员折扣
                        if (isset($levelTwo) && $levelTwo > $userFindTwo['profit_level']) {
                            $updataTwo['profit_level'] = $levelTwo;
                            M('users')->where("user_id", $v['user_id'])->save($updataTwo);
                        }
                        // 如果有微信公众号 则推送一条消息到微信
                        $wx_content = '恭喜您：你的二级分销商' . shownickname($user_id['nickname']) . '，购买了您分享的商品【' . $goods['goods_name'] . '】，你所分得的收益为：' . $money_two . '元。';
                        $wx_tplarr=array (
                            'first' => 
                            array (
                              'value' => '恭喜您：你的二级分销商' . shownickname($user_id['nickname']).'已购买了您分享的商品哦',
                              'color' => '#333',
                            ),
                            'keyword1' => 
                            array (
                              'value' => '【' . $goods['goods_name'] . '】',
                              'color' => '#333',
                            ),
                            'keyword2' => 
                            array (
                              'value' =>  $money_two ,
                              'color' => '#333',
                            ),
                            'keyword3' => 
                            array (
                              'value' => '已确认收货' ,
                              'color' => '#333',
                            ),
                            'remark' => 
                            array (
                              'value' => '感谢您的参与，你随时可以在可用余额中提取您的佣金！',
                              'color' => '#333',
                            )
                         );
                         $url='/mobile/User/points/type/all.html';
                        push_wxtplmessage($share_two['user_id'],$wx_tplarr,$url,'distribut');
                        //push_wxmessage($share_two['user_id'], $wx_content);
                    }
                    if($agent_moneys){
      
                        foreach ($agent_moneys as $kk => $va) {
                            $agentdata['agent_id'] = $va['agent_id'];
                            $agentdata['money'] =$va['money'];
                            $agentdata['change_time'] = time();
                            $agentdata['desc'] = "代理商利润";
                            $agentdata['rec_id'] = $goods['rec_id'];
                            $agentdata['order_id'] = $goods['order_id'];
                            $acc_agent = M('agent_account_log')->add($agentdata);
                        }    
                    }
                }
                       
            }else{
                //当没有分销存在的时候
                if($agents){
                    $agent_discount=M('agents a')->join('agent_level b','a.level_id=b.level_id','left')->where(['a.agent_id'=>$this->weixin_config['agent_id']])->getField('discount');
                    foreach($orderList as $k=>$v){
                            //计算代理商收入金额
                            $good_price=$v['goods_price']*$agent_discount/100;
                            $agent_money=bcsub($v['member_goods_price'],$good_price,2)*$v['goods_num'];
                            $agentdata['agent_id'] = $this->weixin_config['agent_id'];
                            $agentdata['money'] =$agent_money;
                            $agentdata['change_time'] = time();
                            $agentdata['desc'] = "代理商利润";
                            $agentdata['rec_id'] = $v['rec_id'];
                            $agentdata['order_id'] = $v['order_id'];
                            $acc_agent = M('agent_account_log')->add($agentdata);

                            //计算父级代理商收入金额
                            if($parent_agent&&$parent_agent['is_check']>0){
                                $parent_discount=M('agents a')->join('agent_level b','a.level_id=b.level_id','left')->where(['a.agent_id'=>$parent_agent['agent_id']])->getField('discount');
                                $agentdata['agent_id']=$parent_agent['agent_id'];
                                $agentdata['money']=$v['goods_price']*$v['goods_num']*($agent_discount-$parent_discount)/100;
                                $agentdata['desc'] = "代理商利润";
                                $acc_agent = M('agent_account_log')->add($agentdata);
                            }
                            
                    }
                }
            }

            $model = new UsersLogic();
            $order_goods = $model->get_order_goods($id);
            $user = get_user_id();
            $this->assign('user',$user['user_id']);
            $this->assign('order_goods', $order_goods);
            //var_dump($order_goods);
            return $this->fetch();
            exit;
        }
    }


   /* function update_user_level($user_id){
        $level_info = M('user_level')->order('level_id')->select();
        $order = M('order')->where("user_id=:user_id AND pay_status=1 and order_status not in (3,5)")->bind(['user_id'=>$user_id])->order('order_id desc')->find();
        $order_point = M('order_goods')->where("order_id", $order['order_id'])->sum("give_integral * goods_num");
        $user_point = M('users')->field('point_amount')->where('user_id',$user_id)->find();
        $total_amount = $order_point + $user_point['point_amount'];
        if($order_point){
            foreach($level_info as $k=>$v){
                if($total_amount >= $v['amount']){
                    $level = $level_info[$k]['level_id'];
                    $discount = $level_info[$k]['discount']/100;
                }
            }

            $user = session('user');
            $updata['point_amount'] = array("point_amount" => array("exp", "point_amount+".$total_amount));//更新累计修复额度
            //累计额度达到新等级，更新会员折扣
            if(isset($level) && $level>$user['level']){
                $updata['level'] = $level;
                $updata['discount'] = $discount;
            }
            M('users')->where("user_id", $user_id)->save($updata);
        }
    }*/

    /**
     * 申请退货
     */
    public function return_goods()
    {
        $order_id = I('order_id/d', 0);
        $order_sn = I('order_sn', 0);
        $goods_id = I('goods_id/d', 0);
        $good_number = I('good_number/d', 0); //申请数量
        $spec_key = I('spec_key');
        $goods_num = I('goods_num');
        $c = M('order')->where(['order_id' => $order_id, 'user_id' => $this->user_id])->count();
        if ($c == 0) {
            $this->error('非法操作');
            exit;
        }

        $return_goods = M('return_goods')
            ->where(['order_id' => $order_id, 'goods_id' => $goods_id, 'spec_key' => $spec_key])
            ->find();
        $goods_num=M('order_goods')->where(['order_id' => $order_id, 'goods_id' => $goods_id, 'spec_key' => $spec_key])->getField('goods_num');
        if (!empty($return_goods)) {
            $this->success('已经提交过退货申请!', U('Mobile/User/return_goods_info', array('id' => $return_goods['id'])));
            exit;
        }
        if (IS_POST) {
            // 晒图片
            if (count($_FILES['return_imgs']['tmp_name'])>0) {
                $files = request()->file('return_imgs');
                $save_url = 'public/upload/return_goods/' . date('Y', time()) . '/' . date('m-d', time());
                foreach ($files as $file) {
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->rule('uniqid')->validate(['size' => 1024 * 1024 * 3, 'ext' => 'jpg,png,gif,jpeg'])->move($save_url);
                    if ($info) {
                        // 成功上传后 获取上传信息
                        $return_imgs[] = '/'.$save_url . '/' . $info->getFilename();
                    } else {
                        // 上传失败获取错误信息
                        $this->error($file->getError());
                    }
                }
                if (!empty($return_imgs)) {
                    $data['imgs'] = implode(',', $return_imgs);
                }
            }
            $data['order_id'] = $order_id;
            $data['order_sn'] = $order_sn;
            $data['goods_id'] = $goods_id;
            $data['addtime'] = time();
            $data['user_id'] = $this->user_id;
            $data['type'] = I('type'); // 服务类型  退货 或者 换货
            $data['reason'] = I('reason'); // 问题描述
            $data['spec_key'] = I('spec_key'); // 商品规格
            $data['goods_num'] = I('goods_num'); // 商品规格
            $res = M('return_goods')->add($data);
            $data['return_id'] = $res;  //退换货id
            $this->assign('data',$data);
            return $this->fetch('return_good_success'); //申请成功
//            $this->success('申请成功,客服第一时间会帮你处理', U('Mobile/User/order_list'));
            exit;
        }

        $region_id[] = tpCache('shop_info.province');
        $region_id[] = tpCache('shop_info.city');
        $region_id[] = tpCache('shop_info.district');
        $region_id[] = 0;
        $return_address = M('region')->where("id in (".implode(',', $region_id).")")->getField('id,name');
        $this->assign('return_address', $return_address);

//        $goods = M('goods')->where("goods_id", $goods_id)->find();
        $goods = M('order_goods')->where("goods_id", $goods_id)->find();
        //查找订单收货地址
        $region = M('order')->field('consignee,country,province,city,district,twon,address,mobile')->where("order_id = $order_id")->find();
        $region_list = get_region_list();
        $this->assign('region_list', $region_list);
        $this->assign('region', $region);
        $this->assign('goods', $goods);
        $this->assign('order_id', $order_id);
        $this->assign('order_sn', $order_sn);
        $this->assign('goods_id', $goods_id);
        $this->assign('goods_num', $goods_num);

        return $this->fetch();
    }

    /**
     * 退换货列表
     */
    public function return_goods_list()
    {
        //退换货商品信息
        $count = M('return_goods')->where("user_id", $this->user_id)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('return_goods')->where("user_id", $this->user_id)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $goods_id_arr = get_arr_column($list, 'goods_id');  //获取商品ID
        if (!empty($goods_id_arr)){
            $goodsList = M('goods')->where("goods_id", "in", implode(',', $goods_id_arr))->getField('goods_id,goods_name');
        }

        $this->assign('goodsList', $goodsList);
        $this->assign('list', $list);
        $this->assign('page', $page->show());// 赋值分页输出
        if (I('is_ajax')) {
            return $this->fetch('ajax_return_goods_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     *  退货详情
     */
    public function return_goods_info()
    {
        $id = I('id/d', 0);
        $return_goods = M('return_goods')->where("id = $id")->find();
        if ($return_goods['imgs'])
            $return_goods['imgs'] = explode(',', $return_goods['imgs']);
        $goods = M('goods')->where("goods_id = {$return_goods['goods_id']} ")->find();
        $this->assign('goods', $goods);
        $this->assign('return_goods', $return_goods);
        return $this->fetch();
    }


    public function recharge()
    {
        $order_id = I('order_id/d');
        $paymentList = M('Plugin')->where("`type`='payment' and code!='cod' and status = 1 and  scene in(0,1)")->select();
        //微信浏览器
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $paymentList = M('Plugin')->where("`type`='payment' and status = 1 and code='weixin'")->select();
        }
        $paymentList = convert_arr_key($paymentList, 'code');

        foreach ($paymentList as $key => $val) {
            $val['config_value'] = unserialize($val['config_value']);
            if ($val['config_value']['is_bank'] == 2) {
                $bankCodeList[$val['code']] = unserialize($val['bank_code']);
            }
        }
        $bank_img = include APP_PATH . 'home/bank.php'; // 银行对应图片
        $payment = M('Plugin')->where("`type`='payment' and status = 1")->select();
        $this->assign('paymentList', $paymentList);
        $this->assign('bank_img', $bank_img);
        $this->assign('bankCodeList', $bankCodeList);

        if ($order_id > 0) {
            $order = M('recharge')->where("order_id", $order_id)->find();
            $this->assign('order', $order);
        }

        $recharge=M('recharge_give')->order('money asc')->select();
        $this->assign('recharge', $recharge);
        return $this->fetch();
    }

    /**
     * 申请提现记录
     */
    public function withdrawals()
    {

        C('TOKEN_ON', true);
        if (IS_POST) {
            //$this->verifyHandle('withdrawals');
            $data = I('post.');
            $data['user_id'] = $this->user_id;
            $data['create_time'] = time();
            $distribut_min = tpCache('basic.min'); // 最少提现额度
            if ($data['money'] < $distribut_min) {
                $this->error('每次最少提现额度' . $distribut_min);
                exit;
            }
            if ($data['money'] > $this->user['distribut_money']) {
                $this->error("你最多可提现{$this->user['distribut_money']}账户余额.");
                exit;
            }
            $withdrawal = M('withdrawals')->where(array('user_id' => $this->user_id, 'status' => 0))->sum('money');
            if ($this->user['distribut_money'] < ($withdrawal + $data['money'])) {
                $this->error('您有提现申请待处理，本次提现余额不足');
            }
            if (M('withdrawals')->add($data)) {
                $this->success("已提交申请");
                exit;
            } else {
                $this->error('提交失败,联系客服!');
                exit;
            }
        }

        $withdrawals_where['user_id'] = $this->user_id;
        $count = M('withdrawals')->where($withdrawals_where)->count();

        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('withdrawals')->where($withdrawals_where)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();
        $user = M('users')->where('user_id',$this->user_id)->find();
        $appcount = M('withdrawals')->where($withdrawals_where)->where('status',0)->sum('money');//申请中的金额
        $remmoney=($user['distribut_money']-$appcount<0)?0:$user['distribut_money']-$appcount;//剩余可申请提现金额
        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('list', $list); // 下线
        if (I('is_ajax')) {
            return $this->fetch('ajax_withdrawals_list');
            exit;
        }
       /* $order_count = M('order')->where("user_id", $this->user_id)->count(); // 我的订单数
        $goods_collect_count = M('goods_collect')->where("user_id", $this->user_id)->count(); // 我的商品收藏
        $comment_count = M('comment')->where("user_id", $this->user_id)->count();//  我的评论数
        $coupon_count = M('coupon_list')->where("uid", $this->user_id)->count(); // 我的优惠券数量
        $level_name = M('user_level')->where("level_id", $this->user['level'])->getField('level_name'); // 等级名称
        $profit_name = M('user_level_distribution')->where("level_id", $this->user['profit_level'])->getField('level_name'); // 收益等级名称
        $district_count =M('share_record t1')->join('tp_goods t2','t1.goods_id=t2.goods_id and t2.is_on_sale=1','left')->join('tp_users t3','t1.s_user_id=t3.user_id','left')->where('t1.user_id = '.$this->user_id.'  or t1.first_user_id = '.$this->user_id)->where('t2.on_time <= '.time().' and t2.off_time >='.time())->count();*/
        //$this->assign('level_name', $level_name);
        //$this->assign('profit_name', $profit_name);
        $this->assign('user',$user);
        //$this->assign('goods_collect_count', $goods_collect_count);
        //$this->assign('comment_count', $comment_count);
        //$this->assign('district_count', $district_count);
        $this->assign('user_money', $user['user_money']);    //用户余额
        $this->assign('remmoney', $remmoney); 
        return $this->fetch();
    }

    public function ajax_withdrawals(){
        $num=I('get.num');
        $this->assign('num',$num);
        $this->assign('user_money', $this->user['user_money']);    //用户余额
        return $this->fetch();
    }

    /**
     * 申请记录列表
     */
    public function withdrawals_list()
    {
        $withdrawals_where['user_id'] = $this->user_id;
        $count = M('withdrawals')->where($withdrawals_where)->count();
        $pagesize = C('PAGESIZE');
        $page = new Page($count, $pagesize);
        $list = M('withdrawals')->where($withdrawals_where)->order("id desc")->limit("{$page->firstRow},{$page->listRows}")->select();

        $this->assign('page', $page->show());// 赋值分页输出
        $this->assign('list', $list); // 下线
        if (I('is_ajax')) {
            return $this->fetch('ajax_withdrawals_list');
            exit;
        }
        return $this->fetch();
    }

    /**
     * 删除已取消的订单
     */
    public function order_del()
    {
        $user_id = $this->user_id;
        $order_id = I('get.order_id/d');
        $order = M('order')->where(array('order_id' => $order_id, 'user_id' => $user_id))->find();
        if (empty($order)) {
            return $this->error('订单不存在');
            exit;
        }
        $res = M('order')->where("order_id=$order_id and order_status=3")->delete();
        $result = M('order_goods')->where("order_id=$order_id")->delete();
        if ($res && $result) {
            return $this->success('成功', "mobile/User/order_list");
            exit;
        } else {
            return $this->error('删除失败');
            exit;
        }
    }

    /**
     * 我的关注
     * $author lxl
     * $time   2017/1
     */
    public function myfocus()
    {
        return $this->fetch();
    }

    /**
     * 待收货列表
     * $author lxl
     * $time   2017/1
     */
    public function wait_receive()
    {
        $where = ' user_id=' . $this->user_id;
        //条件搜索
        if (I('type') == 'WAITRECEIVE') {
            $where .= C(strtoupper(I('type')));
        }
        $count = M('order')->where($where)->count();
        $pagesize = C('PAGESIZE');
        $Page = new Page($count, $pagesize);
        $show = $Page->show();
        $order_str = "order_id DESC";
        $order_list = M('order')->order($order_str)->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        //获取订单商品
        $model = new UsersLogic();
        foreach ($order_list as $k => $v) {
            $order_list[$k] = set_btn_order_status($v);  // 添加属性  包括按钮显示属性 和 订单状态显示属性
            //$order_list[$k]['total_fee'] = $v['goods_amount'] + $v['shipping_fee'] - $v['integral_money'] -$v['bonus'] - $v['discount']; //订单总额
            $data = $model->get_order_goods($v['order_id']);
            $order_list[$k]['goods_list'] = $data['result'];
        }

        //统计订单商品数量
        foreach ($order_list as $key => $value) {
            $count_goods_num = '';
            foreach ($value['goods_list'] as $kk => $vv) {
                $count_goods_num += $vv['goods_num'];
            }
            $order_list[$key]['count_goods_num'] = $count_goods_num;
            //订单物流单号
            $invoice_no = M('DeliveryDoc')->where("order_id", $value['order_id'])->getField('invoice_no', true);
            $order_list[$key][invoice_no] = implode(',', $invoice_no);
        }
        $this->assign('page', $show);
        $this->assign('order_list', $order_list);
        if ($_GET['is_ajax']) {
            return $this->fetch('ajax_wait_receive');
            exit;
        }
        return $this->fetch();
    }

    /**
     *  用户消息通知
     * @author dyr
     * @time 2016/09/01
     */
    public function message_notice()
    {
        return $this->fetch('user/message_notice');
    }

    /**
     * ajax用户消息通知请求
     * @author dyr
     * @time 2016/09/01
     */
    public function ajax_message_notice()
    {
        $type = I('type', 0);
        $user_logic = new UsersLogic();
        $message_model = new Message();
        if ($type == 1) {
            //系统消息
            $user_sys_message = $message_model->getUserMessageNotice();
            $user_logic->setSysMessageForRead();
        } else if ($type == 2) {
            //活动消息：后续开发
            $user_sys_message = array();
        } else {
            //全部消息：后续完善
            $user_sys_message = $message_model->getUserMessageNotice();
        }
        $this->assign('messages', $user_sys_message);
        return $this->fetch('user/ajax_message_notice');

    }

    /**
     * 设置消息通知
     */
    public function set_notice(){
        //暂无数据
        return $this->fetch();
    }

    public function AjaxTime(){
        $id = $this->user_id;
        $user = M('users')->field('distribut_money,profit_level')->find($id);
        $whereRecharge['user_id'] = $id;
        $whereRecharge['pay_status'] = '1';
        $whereRecharge['pay_code'] = 'weixin';
        //充值支付成功的时间
        $recharge = M('recharge')->where($whereRecharge)->field('pay_time')->order('order_id desc')->find();
        //用户所在的分销等级，所需要提现的时间
        $allow_time = M('user_level_distribution')->field('allow_time')->where('level_id',$user['profit_level'])->find();
        if(empty($user['frozen_money'])){
            $data = '0';
        }
        $time = $recharge['pay_time']+(86400*$allow_time['allow_time']);
        if(time() < $time){
            $data = '1';
        }

        $res=accountLog($id, (int)$user['frozen_money'], 0,'解冻分销押金到余额',-(int)$user['frozen_money'],'unfreeze',array('level_id'=>1));
        if($res)
        $data = '2';
        return $data;
    }

    /**
     * 门店销售统计
     */
    public function company_table(){
     if($this->auth!=1){
        exit;
     }
     if(IS_AJAX){
        $start_time=I('post.start_time');
        $end_time=I('post.end_time');
        $shop_list=I('post.shop_list');
        $shop_name=I('post.shop_name');
        $shop_num=I('post.shop_num');
        $start_time=date("Y-m-d",strtotime($start_time)); 
        $end_time=date("Y-m-d",strtotime($end_time));

           try {  
             $hostname = "61.184.202.7"; 
             $port = "1433";  
             $dbname = "interlink";
             $username = "sa";  
             $pw = "interlink_*2017*";  
             $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");  
           } catch (PDOException $e) {  
             echo "Failed to get DB handle: " . $e->getMessage() . "\n";  
             exit;  
           }
           $sql="SELECT * FROM v_dqgj_dpxs  where doc_date between '".$start_time."' and '".$end_time."'";

           if($shop_list=="''"){
            $result=M('v_dqgj_mddzcx')->field('md_name,md_num')->select();
            foreach ($result as $key => $value) {
                $shop_names[]=$value['md_name'];
                $shop_nums[]=$value['md_num'];
            }
           }else{
             $sql.=" and md_num in(".$shop_list.")";
             $shop_names=explode(',', $shop_name);
             $shop_nums=explode(',', $shop_num);
           }
           $sql.=" order by doc_date";

           $stmt = $dbh->prepare($sql);  
           $stmt->execute(); 
           $arrr=array(); 
           while ($row = $stmt->fetch()) { 
            //var_dump($row);
             $key=array_search($row['doc_date'], $arrr);
             if(!$key){
                $arrr[]=$row['doc_date'];
                $key=array_search($row['doc_date'], $arrr);
             }
             $kk=array_search($row['md_num'],$shop_nums);

             $ress[$key][$kk]=$row;
             $ress_arr[$key][$kk]=$row['md_num'];
             ksort($ress[$key]);
           } 

            foreach ($ress_arr as $key => $value) {
                 $c_arr= array_diff_assoc($shop_nums,$value);
                 if(!empty($c_arr)){
                    foreach ($c_arr as $k => $val) {
                        $ress[$key][$k]=array('md_num'=>$val,'sell_val'=>'0.00','doc_date'=>$arrr[$key]);
                        ksort($ress[$key]);
                    }
                 }
                    
             } 
            unset($dbh); unset($stmt);

            
            $htmlstr="<table id='shoptable'><tr><th style='width:100px;white-space:nowrap;'>日期</th>"; 
            foreach ($shop_names as $key => $value) {
               $htmlstr.='<th>'.$value.'</th>';
            }
            $htmlstr.='<th>合计</th></tr>';
           foreach ($ress as $key => $value) {
                $sum1=0;
               $htmlstr.='<tr><td>'.date('Y-m-d',strtotime($value[0]['doc_date'])).'</td>';
               foreach ($value as $k => $val) {
                    $htmlstr.='<td>'.$val['sell_val'].'</td>';
                    $sum1+=$val['sell_val'];
                    if(!isset($sum2[$k])){
                        $sum2[$k]=0;
                    }
                    $sum2[$k]+=$val['sell_val'];
               }
               $htmlstr.='<td>'.sprintf('%.2f',$sum1).'</td></tr>';
           }
           $htmlstr.='<tr style="background:#eee"><td>合计</td>';
           $total=0;
           foreach ($sum2 as $key => $value) {
               $htmlstr.='<td>'.sprintf('%.2f',$value).'</td>';
               $total+=$value;
           }
           $htmlstr.="<td>".sprintf('%.2f',$total)."</td></tr></table>";
         
          echo $htmlstr;
         }else{

            $row=M('v_dqgj_mddzcx')->select();
            foreach ($row as $key => $value) {
                $arr['title']=$value['md_name'];
                $arr['value']=$value['md_num'];
                $list[]=$arr;
            }
            if(isMobile()){
                $is_mobile=1;
            }else{
                $is_mobile=0;
            }

            $this->assign('list', json_encode($list));
            $this->assign('is_mobile', $is_mobile);
            return $this->fetch();
         }  

    }

    public function parse2excel(){
        $txt=I('post.txt');
        $title=I('post.title');

        $txtarr=json_decode($txt,true);
        $title=json_decode($title,true);

        exportexcel($txtarr,$title);
    }

    public function consume_point(){
        $points=I('post.points');
        $goods_id=I('post.goods_id');
        $users=M('users');
        $pay_points=$users->where('user_id',$this->user_id)->getField('pay_points');

        if($pay_points<$points){
                echo "not_points";
                exit;
            }
        $res=accountLog($this->user_id,0,-$points,"消费积分",0,"consume_points");
        if($res){
            echo 'success';
        }

    }
    public function get_card(){

        return $this->fetch();
    }




}

